package light.head.controller.site;

import java.io.FileOutputStream;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.site.OrganActivitiesDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.FileInfo;
import light.head.model.OrganActivities;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * 公司活动 （type 0 公告 1 公司动态 ）
 */
@Controller
@RequestMapping(Url.ORGANACTIVITIES)
public class OrganActivitiesController extends SupporterController {
	private OrganActivitiesDAO oaDAO;
	private final static String organactivities_photo_path = "upload/organactivitiesPhoto/";
	private final static String organactivities_file_path = "upload/organactivitiesFile/";

	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.ORGANACTIVITIES_INIT);
	}

	@RequestMapping(Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.TITLE, Parm.NAME, Parm.TIME1, Parm.TIME2, Parm.TYPE, Parm.DELETED,Parm.OC);
		if (oaDAO.findByMap(map, pb) == RESULT.SUCCESS) {
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.ORGANACTIVITIES_LIST);
	}

	@RequestMapping(Url.EDIT)
	public ModelAndView edit(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			OrganActivities oa = oaDAO.get(code);
			request.setAttribute(Parm.ORGANACTIVITIES, oa);
		}
		return new ModelAndView(Url.ORGANACTIVITIES_DEIT);
	}

	@RequestMapping(value = Url.SAVE)
	public void save(OrganActivities oa, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (oa.getCode() != null) {
			result = oaDAO.upd(oa);
		} else {
			Date date = new Date();
			oa.setDeleted(false);
			oa.setCt(date);
			oa.setTopTime(date);
			oa.setCu(cu_code(request));
			result = oaDAO.add(oa);
		}
		if (result == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}

	@RequestMapping(value = Url.DELETE)
	public void delete(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (code != null) {
			OrganActivities oa = oaDAO.get(code);
			oa.setDeleted(true);
			result = oaDAO.upd(oa);
		}
		if (result == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}
	//置顶公告 或 公司动态
	@RequestMapping(value = Url.ORGANACTIVITIESTOP)
	public void organActivitiesTop(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (code != null) {
			OrganActivities oa = oaDAO.get(code);
			oa.setTopTime(new Date());
			result = oaDAO.upd(oa);
		}
		if (result == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}

	// 单个文件保存
	@Transactional
	@RequestMapping(Url.UPLOAD)
	public void upload(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile pohto = multipartRequest.getFile(Parm.UPLOAD);
		String type = request.getParameter(Parm.TYPE);
		String name = pohto.getOriginalFilename();
		if (isNotNull(name)) {
			String ext = name.substring(name.lastIndexOf(Sys.DOT) + 1);
			if (!ext.toUpperCase().equals(Sys.JPG)
					&& !ext.toUpperCase().equals(Sys.GIF)
					&& !ext.toUpperCase().equals(Sys.JPEG)
					&& !ext.toUpperCase().equals(Sys.BMP)
					&& !ext.toUpperCase().equals(Sys.PNG)
					&& !ext.toUpperCase().equals(Sys.XLSX)
					&& !ext.toUpperCase().equals(Sys.XLS)
					&& !ext.toUpperCase().equals(Sys.DOCX)
					&& !ext.toUpperCase().equals(Sys.DOC)
					&& !ext.toUpperCase().equals(Sys.PDF)
					&& !ext.toUpperCase().equals(Sys.PPT)
					&& !ext.toUpperCase().equals(Sys.RAR)
					&& !ext.toUpperCase().equals(Sys.ZIP)) {
				print(response, Msg.J_FILE_TYPE_ERROR);
				return;
			}
			name = name.substring(0, name.lastIndexOf(Sys.DOT));

			UUID u = UUID.randomUUID();
			String uuid = u.toString().replace("-", "");
			String path = (type.equals(Sys.FILE) ? organactivities_file_path : organactivities_photo_path) + uuid + Sys.DOT + ext;
			String savePath = ConfigParm.getProjectPath() + path;
			FileOutputStream fo;
			int size = 0;
			try {
				fo = new FileOutputStream(savePath);
				size = pohto.getBytes().length;
				fo.write(pohto.getBytes());
				fo.close();
			} catch (Exception e) {
				print(response, Msg.J_ERROR);
				e.printStackTrace();
				throw new RuntimeException();
			}

			FileInfo f = new FileInfo();
			f.setDeleted(false);
			f.setExt(ext);
			f.setName(name);
			f.setUuid(uuid);
			f.setCt(new Date());
			if (type.equals(Sys.FILE)) {
				f.setType(Sys.B_ONE);
				f.setModule(Parm.ORGANACTIVITIESFILE);
			} else {
				f.setType(Sys.B_TWO);
				f.setModule(Parm.ORGANACTIVITIESPHOTO);
			}

			f.setCu(cu_code(request));
			f.setOc(cu_organCode(request));
			f.setSize(size);
			oaDAO.add(f);

			StringBuffer result = new StringBuffer();
			result.append("<script type=\"text/javascript\">");
			if (isNotNull(path)) {
				result.append("window.parent.CKEDITOR.tools.callFunction("+ request.getParameter("CKEditorFuncNum") + ",'" + path + "',''" + ")");
				result.append("</script>");
				result.append(path);
			} else {
				result.append("alert(\"上传失败，文件类型需要jpg、gif或png\")");
				result.append("</script>");
			}
			response.setHeader("Content-Type", "text/html; charset=UTF-8");
			print(response, result.toString());

		} else {
			print(response, Msg.J_ERROR);
		}
	}

	@Autowired
	public void setOaDAO(OrganActivitiesDAO oaDAO) {
		this.oaDAO = oaDAO;
	}
}
